<?php
namespace App\Utils;

use App\Module\Base;
use App\Module\Users;

class ThirdLoginUtil {

    /**
     * @param string $username
     * @param string $password
     * @return array
     */
    public static function doLogin(string $username, string $password): array
    {
        $config = self::getConfig();

        //暂时只支持 form ，后续考虑支持 OAuth2.0等
        if($config['type'] == 'form'){
            $formConfig = $config['form'];

            // 准备请求
            $data = http_build_query(
                array($formConfig['key_param_username'] => $username,
                    $formConfig['key_param_password'] => $password)
            );
            $opts = array('http' => array('method' => $formConfig['method'], 'header' => 'Content-type: '.$formConfig['content_type'] , 'content' => $data));
            $context = stream_context_create($opts);
            // 发送请求，解析结果
            $html = file_get_contents($formConfig['url'], false, $context);
            $result = json_decode($html,true);

            // 判断是否成功
            $result_code_key = $formConfig['key_result_code'];
            if($formConfig['value_result_code'] == $result[$result_code_key]){
                $other = array("nickname" => $result[$formConfig['key_result_data']][$formConfig['key_result_nickname']]);
                return Users::reg($username, $password, $other);
            }
            return Base::retError('third:'.$result['message']);
        }
        return Base::retError('not support type');;
    }

    /**
     * @return mixed
     */
    public static function getConfig()
    {
        $json = env('LOGIN_THIRD_CONFIG_JSON');
        return json_decode($json,true);
    }

}
